package com.chookss.mine.system;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.tools.NavigationTools;
import com.google.gson.reflect.TypeToken;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.mine.personal.PersonalHomeActivity;
import com.chookss.mine.adapter.MyPraiseAdapter;
import com.chookss.mine.entity.PraiseEntity;
import com.chookss.mine.entity.RecommendVedioEmployeeEntity;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.Utils;
import com.chookss.tools.VedioClassUtils;
import com.chookss.video.VideoOnePlayActivity;
import com.chookss.video.entity.VideoEntity;
import com.chookss.view.CircleImageView;
import com.chookss.view.RecycleViewDivider;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.jetbrains.annotations.Nullable;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

//点赞  粉丝 评论 上半部一个接口，   关注  收藏 上半部一个接口
// 粉丝 关注 下上半部一个接口，   点赞   评论 下半部一个接口
public class MyPraiseActivity extends BaseAct {
    @BindView(R.id.common_title_txt)
    TextView tvTitle;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.smrRf)
    SmartRefreshLayout smrRf;
    @BindView(R.id.rvReommend)
    RecyclerView rvReommend;
    @BindView(R.id.llReommend)
    LinearLayout llReommend;
    private int currentPage = 1;
    private String pageSize = "20";
    private List<RecommendVedioEmployeeEntity> recommendEmployeeEntities = new ArrayList<>();
    private List<RecommendVedioEmployeeEntity> recommendSelects = new ArrayList<>();
    private int indexRecommend = 0; //推荐列表下标在总数据的位置
    private List<PraiseEntity> praiseEntities = new ArrayList<>();
    private TextView tvEmpty;
    private MyPraiseAdapter praiseAdapter;
    private MyRecommendAdapter recommendAdapter;
    private View empty_view;
    private boolean isEnd = false;//是否到底
    private int messageType = 2;//1：粉丝关注通知，2：点赞通知，3：评论通知，5关注

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_fans);
        messageType = getIntent().getIntExtra("messageType", 0);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, Utils.dip2px(this, 0.5f), getResources().getColor(R.color.line_gray)
        ));
        praiseAdapter = new MyPraiseAdapter(R.layout.item_my_fans, this, praiseEntities, messageType);
        recyclerView.setAdapter(praiseAdapter);
        empty_view = LayoutInflater.from(this).inflate(R.layout.layout_fans_empty, recyclerView, false);
        tvEmpty = empty_view.findViewById(R.id.tvEmpty);
        if (1 == messageType) {
            tvTitle.setText("粉丝");
            tvEmpty.setText("暂无粉丝");
        } else if (3 == messageType) {
            tvTitle.setText("评论");
            tvEmpty.setText("暂无评论");
        } else if (5 == messageType) {
            tvTitle.setText("关注");
            tvEmpty.setText("暂无关注");
        } else {
            tvTitle.setText("点赞");
            tvEmpty.setText("暂无点赞");
        }

        rvReommend.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recommendAdapter = new MyRecommendAdapter(R.layout.item_my_recommend, this, recommendSelects);
        rvReommend.setAdapter(recommendAdapter);
        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                currentPage = 1;
                isEnd = false;
                getData();
            }
        });
        smrRf.autoRefresh();
        getRecommendEmployee(true);
        NavigationTools.setWaterMark(this, "19");
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize);
        if (messageType == 5) {
            //关注
            map.put("messageType", "1");
            MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<PraiseEntity>>>() {
            }.getType(), null, Urls.getMyItemByType, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<PraiseEntity>>() {
                @Override
                public void onSuccess(List<PraiseEntity> data) {
                    if (currentPage == 1) {
                        praiseEntities.clear();
                        praiseAdapter.notifyDataSetChanged();
                    }
                    if (data != null && data.size() > 0) {

                        praiseEntities.addAll(data);
                        praiseAdapter.notifyDataSetChanged();

                    } else {
                        isEnd = true;
                        if (praiseEntities.size() == 0) {
                            praiseAdapter.setEmptyView(empty_view);
                        }
                    }
                    loadEnd();
                }

                @Override
                public void onError(String errorMsg) {
                    loadEnd();
                    MyToast.show(Utils.onErrorTips(errorMsg));
                }
            });
        } else {
            //        1：粉丝关注通知，2：点赞通知，3：评论通知
            map.put("messageType", messageType + "");
            MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<PraiseEntity>>>() {
            }.getType(), null, Urls.getMyMessageByType, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<PraiseEntity>>() {
                @Override
                public void onSuccess(List<PraiseEntity> data) {
                    if (currentPage == 1) {
                        praiseEntities.clear();
                        praiseAdapter.notifyDataSetChanged();
                    }
                    if (data != null && data.size() > 0) {

                        praiseEntities.addAll(data);
                        praiseAdapter.notifyDataSetChanged();

                    } else {
                        isEnd = true;
                        if (praiseEntities.size() == 0) {
                            praiseAdapter.setEmptyView(empty_view);
                        }
                    }
                    loadEnd();
                }

                @Override
                public void onError(String errorMsg) {
                    loadEnd();
                    MyToast.show(Utils.onErrorTips(errorMsg));
                }
            });
        }

    }

    private void getRecommendEmployee(boolean isFirst) {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", "1");
        map.put("pageSize", "30");
        String url = null;
        if (messageType == 2 || messageType == 3) {
//            2：点赞通知，3：评论通知
            url = Urls.getRecommendVideo;
            MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<RecommendVedioEmployeeEntity>>>() {
            }.getType(), null, url, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<RecommendVedioEmployeeEntity>>() {
                @Override
                public void onSuccess(List<RecommendVedioEmployeeEntity> data) {
                    if (data != null && data.size() > 0) {
                        recommendEmployeeEntities.addAll(data);
                        if (llReommend == null) {
                            return;
                        }
                        if (isFirst) {
                            if ((recommendEmployeeEntities.size() - indexRecommend) >= 3) {
                                indexRecommend = 3;
                                recommendSelects.addAll(recommendEmployeeEntities.subList(0, 3));
                            } else {
                                indexRecommend = recommendEmployeeEntities.size();
                                recommendSelects.addAll(recommendEmployeeEntities);
                            }
                            if (llReommend != null) {
                                recommendAdapter.notifyDataSetChanged();
                                llReommend.setVisibility(View.VISIBLE);
                            }
                        }
                    } else {
                        if (llReommend == null) {
                            return;
                        }
                        if (recommendEmployeeEntities.size() == 0) {
                            llReommend.setVisibility(View.GONE);
                        }
                    }
                }

                @Override
                public void onError(String errorMsg) {
                    if (llReommend != null) {
                        llReommend.setVisibility(View.GONE);
                        MyToast.show(Utils.onErrorTips(errorMsg));
                    }

                }
            });
        } else {
            // 1：粉丝 5关注
            url = Urls.getRecommendEmployee;
            MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<RecommendVedioEmployeeEntity>>>() {
            }.getType(), null, Urls.getRecommendEmployee, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<RecommendVedioEmployeeEntity>>() {
                @Override
                public void onSuccess(List<RecommendVedioEmployeeEntity> data) {
                    if (data != null && data.size() > 0) {
                        recommendEmployeeEntities.addAll(data);
                        if(llReommend==null){
                            return;
                        }
                        if (isFirst) {
                            if ((recommendEmployeeEntities.size() - indexRecommend) >= 3) {
                                indexRecommend = 3;
                                recommendSelects.addAll(recommendEmployeeEntities.subList(0, 3));
                            } else {
                                indexRecommend = recommendEmployeeEntities.size();
                                recommendSelects.addAll(recommendEmployeeEntities);
                            }
                            if (llReommend != null) {
                                recommendAdapter.notifyDataSetChanged();
                                llReommend.setVisibility(View.VISIBLE);
                            }
                        }
                    } else {
                        if (recommendEmployeeEntities.size() == 0) {
                            if (llReommend != null) {
                                llReommend.setVisibility(View.GONE);
                            }
                        }
                    }
                }

                @Override
                public void onError(String errorMsg) {
                    if (llReommend != null) {
                        llReommend.setVisibility(View.GONE);
                        MyToast.show(Utils.onErrorTips(errorMsg));
                    }

                }
            });
        }


    }

    private void getNewRecommendData(int position) {
        if (position == -1) {
            //换一批三个
            recommendSelects.clear();
            if ((recommendEmployeeEntities.size() - indexRecommend) >= 3) {
                recommendSelects.addAll(recommendEmployeeEntities.subList(indexRecommend, indexRecommend + 3));
                indexRecommend = indexRecommend + 3;
            } else if (indexRecommend < recommendEmployeeEntities.size()) {
                indexRecommend = recommendEmployeeEntities.size();
                recommendSelects.addAll(recommendEmployeeEntities.subList(indexRecommend, recommendEmployeeEntities.size()));
            }
        } else {
            recommendSelects.remove(position);
            if ((recommendEmployeeEntities.size() - indexRecommend) >= 1) {
                recommendSelects.addAll(recommendEmployeeEntities.subList(indexRecommend, indexRecommend + 1));
                indexRecommend = indexRecommend + 1;
            }
        }
        recommendAdapter.notifyDataSetChanged();
        if (recommendSelects.size() == 0) {
            llReommend.setVisibility(View.GONE);
        }
        if (recommendEmployeeEntities.size() - indexRecommend <= 10) {
            getRecommendEmployee(false);
        }
    }

    class MyRecommendAdapter extends BaseQuickAdapter<RecommendVedioEmployeeEntity, BaseViewHolderEx> {
        private Context context;

        public MyRecommendAdapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable List<RecommendVedioEmployeeEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, RecommendVedioEmployeeEntity item) {
            CircleImageView ivHead = helper.getView(R.id.ivHead);
            RelativeLayout rlDelete = helper.getView(R.id.rlDelete);
            LinearLayout llContent = helper.getView(R.id.llContent);
            TextView tvName = helper.getView(R.id.tvName);
            TextView tvContent = helper.getView(R.id.tvContent);
            TextView tvTime = helper.getView(R.id.tvTime);
            TextView tvFocus = helper.getView(R.id.tvFocus);
            if (messageType == 2 || messageType == 3) {
                //            2：点赞通知，3：评论通知
                tvName.setText(item.getVideoTitle());
                tvContent.setText("来自" + item.getEmployeeName());
                if ("0".equals(item.getYouIsfans())) {
                    tvTime.setVisibility(View.GONE);
                } else {
                    tvTime.setVisibility(View.VISIBLE);
                    tvTime.setText("已关注好友");
                }
                tvFocus.setText("去看看");
                tvFocus.setBackgroundResource(R.drawable.shape_white_cccccc_12);
                tvFocus.setTextColor(Color.parseColor("#333333"));
            } else {
                // 1：粉丝 5关注
                tvName.setText(item.getNickName());
                if ("0".equals(item.getIsfans())) {
                    llContent.setVisibility(View.GONE);
                    if ("0".equals(item.getYouIsfans())) {
                        tvFocus.setBackgroundResource(R.drawable.shape_white_main_color_12);
                        tvFocus.setTextColor(getResources().getColor(R.color.main_color));
                        tvFocus.setText("关注");
                    } else {
                        tvFocus.setBackgroundResource(R.drawable.shape_white_cccccc_12);
                        tvFocus.setTextColor(Color.parseColor("#333333"));
                        tvFocus.setText("已关注");
                    }
                    tvTime.setText("");
                } else {
                    llContent.setVisibility(View.VISIBLE);
                    tvContent.setText("关注了你");
                    if ("0".equals(item.getYouIsfans())) {
                        tvFocus.setBackgroundResource(R.drawable.shape_white_main_color_12);
                        tvFocus.setTextColor(getResources().getColor(R.color.main_color));
                        tvFocus.setText("关注");
                    } else {
                        tvFocus.setBackgroundResource(R.drawable.shape_white_cccccc_12);
                        tvFocus.setTextColor(Color.parseColor("#333333"));
                        tvFocus.setText("互相关注");
                    }
                    tvTime.setText(Utils.getAccurateDate(item.getConcernTime()));
                }

            }
            GlideUtils.loadAvatar(context, item.getHeadPhotoThumbUrl(), ivHead);
            ivHead.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, PersonalHomeActivity.class);
                    intent.putExtra("employeeCode", item.getEmployeeCode());
                    context.startActivity(intent);
                }
            });
            rlDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getNewRecommendData(helper.getItemPosition());
                }
            });
            tvFocus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (messageType == 1 || messageType == 5) {
                        //关注  粉丝
                        if ("0".equals(item.getYouIsfans())) {
                            toFollow("1", item, helper.getItemPosition());
                        } else {
                            toFollow("0", item, helper.getItemPosition());

                        }
                    } else {
                        VideoEntity video = VedioClassUtils.modelA2RecommendVedioEmployeeEntity(item);
                        if (video == null) {
                            return;
                        }
                        Intent intent = new Intent(context, VideoOnePlayActivity.class);
                        intent.putExtra("video", video);
                        startActivity(intent);
                    }

                }
            });

        }
    }

    private void toFollow(String followStatus, RecommendVedioEmployeeEntity praiseEntity, int position) {
        Map<String, String> map = new HashMap<>();
        map.put("employeeCode", praiseEntity.getEmployeeCode());
        map.put("followStatus", followStatus);
//        状态 0取消 1 关注
        MyHttpRequest.getDefault().postRequestCompat(null, Urls.toFollow, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) throws Exception {
                JSONObject reObject = new JSONObject(data);
                if ("200".equals(reObject.getString("code"))) {
                    JSONObject result_object = reObject.getJSONObject("data");
                    if ("true".equals(result_object.getString("rst"))) {
                        if ("1".equals(followStatus)) {
                            praiseEntity.setYouIsfans("1");
                            MyToast.show("关注成功");
                        } else {
                            praiseEntity.setYouIsfans("0");
                            MyToast.show("取消关注");
                        }
                        recommendAdapter.notifyItemChanged(position);
                    } else {
                        MyToast.show(reObject.getString("msg"));
                    }
                } else {
                    MyToast.show(reObject.getString("msg"));
                }

            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }

    @OnClick({R.id.common_title_back, R.id.tvChange})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.tvChange:
                getNewRecommendData(-1);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (tvTitle != null) {
            Utils.hideInputKeyboard(this, tvTitle);
        }
    }
}
